package org.plumecache.samples;

import com.alibaba.fastjson.JSON;
import com.plumecache.core.CacheService;
import com.plumecache.core.interceptor.BaseCacheInterceptor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;

@Slf4j
public class SlowCacheInterceptor extends BaseCacheInterceptor {

    @Override
    public boolean preHandle(CacheService target, Method method, Object[] args, Map<String, Object> context) {
        Instant begin = Instant.now();
        context.put("SlowCacheInstantBegin", begin);
        return true;
    }

    @Override
    public void postHandle(CacheService target, Method method, Object[] args, Map<String, Object> context, Object result) {
        Instant begin = (Instant) context.get("SlowCacheInstantBegin");

        if (Duration.between(begin, Instant.now()).toMillis() > 5) {
            log.warn("[SlowCacheInterceptor]slow cache, method:{},args:{},result:{},cost:{}"
                    , method.getDeclaringClass().getName() + "." + method.getName()
                    , JSON.toJSONString(args)
                    , JSON.toJSONString(result)
                    , Duration.between(begin, Instant.now()).toMillis());

            //do something others
        }
    }
}
